/**
 * 
 */
package com.mvc.service.mb.impl;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.huangqj.consant.StringUtils;
import org.huangqj.consant.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.mvc.dao.BaseDaoI;
import com.mvc.dao.mapper.BaseInfoDao;
import com.mvc.framework.constant.GlobalConstant;
import com.mvc.model.base.BaseData;
import com.mvc.model.base.SessionInfo;
import com.mvc.model.mb.archive.BaseInfo;
import com.mvc.service.healthmanager.PersonIdServiceI;
import com.mvc.service.mb.BaseInfoServiceI;
import com.mvc.utils.AddressUtils;
import com.mvc.utils.Ch2PinYin;
import com.mvc.utils.MD5Util;
import com.mvc.utils.StringUtil;

/**
 * @author qingjie
 *
 */
@Service
public class BaseInfoServiceImpl implements BaseInfoServiceI {
	@Autowired
	private BaseDaoI<BaseInfo> baseDaoI;
	@Autowired
	private BaseInfoDao bInfoDao;
	@Autowired
	private PersonIdServiceI psi;
	
	@Override
	public List<BaseInfo> getBaseInfo(String idcard) {
		BaseInfo bi = new BaseInfo();
		String mobile = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9])|(17[0-9]))\\d{8}$"; 
		String email = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
		String card =  "(^\\d{18}$)|(^\\d{15}$)";
		if(idcard!=null){
			//手机登录
			if(idcard.matches(mobile)){
				bi.setMobile(idcard);
			//邮箱登陆	
			}else if(idcard.matches(email)){
				bi.setEmail(idcard);
			//身份证号码登陆	
			}else if(idcard.matches(card)){
				bi.setIdcard(idcard);
			//企业名称登陆	
			}else bi.setCompany(idcard);
		}
		return bInfoDao.getBaseInfo(bi);
	}

	@Override
	public List<BaseInfo> getBaseInfos(String personId) {
		String[] personIds = JSON.parseObject(personId, String[].class);
		List<BaseInfo> list = new ArrayList<BaseInfo>();
		for(String id:personIds){
			BaseInfo bi = baseDaoI.get("from BaseInfo where personId = '"+id+"'");
			if(bi!=null){
				bi.setAge(StringUtil.getAge(ValidatorUtil.sdf.format(bi.getBirthDate())));
				list.add(bi);
			}
		}
		return list;
	}

	@Override
	public BaseInfo updateBaseInfo(BaseInfo baseInfo) {
		List<BaseInfo> list = getBaseInfo(baseInfo.getIdcard());
		if(list.size()>0){
			baseInfo = list.get(0);
			baseInfo.setIsHave(true);
		}else{
			SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
			String max = psi.getMaxStr(baseInfo.getCreatfileDepId());
			String nations = StringUtils.getMapKeys(GlobalConstant.nations, (ValidatorUtil.isBlankOnString(baseInfo.getNation())?"汉族":"")+",", ",");
			baseInfo.setNation(ValidatorUtil.isBlankOnString(nations)?"1":"2");
			baseInfo.setNations(nations);
			baseInfo.setSex(baseInfo.getSex());
			baseInfo.setPersonId(max);
			baseInfo.setFileState("0");
			baseInfo.setShortName(!ValidatorUtil.isBlankOnString(baseInfo.getName())?Ch2PinYin.getFirstCh(baseInfo.getName()):"");
			baseDaoI.saveOrUpdate(baseInfo);
			baseInfo.setIsHave(false);
		}
		return baseInfo;
	}

	@Override
	public boolean editUserPwd(SessionInfo sessionInfo, String oldPwd,String pwd) {
		BaseInfo b = baseDaoI.get(BaseInfo.class, sessionInfo.getId());
		if (b.getPatientPwd().equalsIgnoreCase(MD5Util.md5(oldPwd))) {// 说明原密码输入正确
			b.setPatientPwd(MD5Util.md5(pwd));
			return true;
		}
		return false;
	}

	/**
	 * @author qingjie
	 * 用户注册
	 * @param bi
	 */
	@Override
	public String register(BaseInfo bi,String ip) {
		BaseInfo bInfo = new BaseInfo();
		String personId = "";
		//密码加密
		bi.setPatientPwd(MD5Util.md5(bi.getPatientPwd()));
		//创建时间
		bi.setCreatfileDate(new Date());
		AddressUtils addressUtils = new AddressUtils();
		try {
			//获取地址字符串
			String str = addressUtils.getAddresses("ip="+ip, "utf-8");
			if(str!=null&&str!="0"){
				//转为数组
				String s[] = str.split(",");
				//拼接字符串
				String param = "%"+s[3]+"%"+s[4]+"%";
				//查询地址域code
				String addressCode = bInfoDao.getAddressCode(param);
				//拼接查询的personid
				bInfo.setPersonId(addressCode+"%");
				//查询结果
				List<BaseInfo> list = bInfoDao.getBaseInfo(bInfo);
				//若存在结果
				if(list.size()>0){
					//存在地域代码，则进行拼接，否则自动拼接16位字符
					if(addressCode!=null){
						personId = addressCode+StringUtil.formatString(4, list.size()+1);
					}else personId = StringUtil.formatString(16, list.size()+1);
				}else personId = StringUtil.formatString(16, 1);
			}else{
				List<BaseInfo> list = bInfoDao.getBaseInfo(bInfo);
				if(list.size()>0){
					personId = StringUtil.formatString(16, list.size()+1);
				}else personId = StringUtil.formatString(16, 1);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//设置个人id
		bi.setPersonId(personId);
		baseDaoI.saveOrUpdate(bi);
		return bi.getId()+"";
	}

	@Override
	public List<BaseInfo> findBaseInfos(BaseInfo bi) {
		Map<String, Object> params = StringUtil.beanToMap(bi);
		return baseDaoI.find(StringUtil.getHql("BaseInfo", params, "asc"), params);
	}

}
